<?php
/**
 * Created by xiaosong
 * E-mail:306027376@qq.com
 * Date: 2018/11/12
 * Time: 17:37
 */

namespace app\api\controller;


use app\common\logic\Bankroll;
use app\common\logic\Logic;
use app\common\model\MemberConfig;
use app\common\service\AppService;
use think\Db;
use think\Env;
use think\Exception;
use think\Log;
use Yansongda\Pay\Pay;

class Pays extends User
{


    protected $checkMember = false;

    protected $prefix = 'BX';
    protected $title  = '伴心';

    protected $alipay = [
        'app_id' => '2018121962575627',
        'notify_url' => 'https://api.mengpaxing.com/pays/notify',
//        'ali_public_key'   => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAiF4Y1bF3uVl6+xdUE+HqeG6HkiRsmnvnszkqv4v9iHrQJHpp7r9GXd1QO51MKjvU3OBOI6I/RLxADtaL8RmQ4AIHYdye5GreITFivbXIMtTprG0AF8gCw8tjWTD+iwuYgbXDh+OniKR3Dks2IEDiwOHilnNGCbib0CIwXDodPxq/avOMMguVxHfsVVIVvzxmaFKun9h8IVC4JGuXaLgV0AHrmqgk7zsTdMQ1pn9AGAh/tW4MC+wb4VPSuDCexU+GSktZZEQU5DBk/mTR+9VuLWDLyEU34sspvlb3TnmDMvPsnA+WxSXSGQeyyk+T2u1tz5/YLTnJ4KzusKwUz+MPSQIDAQAB',
        'ali_public_key'   => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnZrKxbHgYhvT8bUnQXZKKsYKhMKFRSBWRiykrQsiUL5duOaG/sieHG65GOtcqzIsPWH2EMO9UkTekEKoepQAL1orbd3IEOd2aJyc057jMuqZ+KQ10hxJg6LBqQMDbz14QmI3N93SmtrIL1HdavazuU3siXJdYCKLkPqJREPovTXBoI3rTOyQ+gmbDWS6itroySsXugWIjMlHk0WJZdSct+ahQJt6nU+7H07QI+OFYolzwx5FXmQRGNlfVfc5YOHrnNFokoYkm+mj/hcMNsfUHCFuyzgXCH5yjO1zAFbfg2nmrEhd7xEHchbTbDisGxyzE415m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QyhSVIzmEJ6XUrNeC',
    ];

    protected  $wechat = [

        'appid' => 'wxf0067f2467b87fb3', // APP APPID
        'app_id' => 'wxf0067f2467b87fb3', // APP APPID
//        'mch_id' => '1521927091',
        'mch_id' => '1520744671',
        'key' => 'e10adc3949ba59abbe56e057f20f883e',
        'notify_url' => 'https://api.mengpaxing.com/pays/wechat',
        'cert_client' => './apiclient_cert.pem', // optional，退款等情况时用到
        'cert_key' => './apiclient_key.pem',// optional，退款等情况时用到
    ];


    public function _initialize()
    {
        parent::_initialize();
        if (!empty(config('ali_url'))){
            $this->alipay['notify_url'] = config('ali_url');
        }
        if (!empty(config('wechat_url'))){
            $this->wechat['notify_url'] = config('wechat_url');
        }
    }

    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 支付签名获取
     */
    public function paySign()
    {
        $this->ApiLimit(1,$this->user_id);

        $data = input('post.');

        $order_num = $this->prefix.hashid($this->user_id).time().rand(1000,9999);

        switch ($data['type']){
            case 'recharge': //钻石充值
                $map['r_id']   = $data['id'];
                $map['status'] = 1;
                $config = Db::name('recharge_config')->where($map)->find();
                if (!$config || $config['price'] <= 0) api_return(0,'参数错误');

                //首充
                $con['user_id'] = $this->user_id;
                $con['pay_type'] = 3;

                $first = Db::name('bankroll')->where($con)->find();

                if ($first){
                    $is_first = 1;
                }else{
                    $is_first = 0;
                }

                $price   = $config['price'];
                $subject = $this->title.'充值'.$config['money'].'钻';

                $body = json_encode([
                    'user_id' => hashid($this->user_id),
                    'id'      => $data['id'],
                    'type'    => $data['type'],
                    'remark'  => $subject,
                    'subject' => $subject,
                    'is_first' => $is_first,
                    'pay_type' => 3
                ]);

                break;
            case 'gift': //礼物赠送
                $array   = $this->giveGift($data,$this->user_id);
                $price   = $array['price'];
                $subject = $array['subject'];


                $body = json_encode($array);
                break;
            case 'invite': //邀约订单付款

                $map['order_id'] = $data['order_id'];
                $map['status']   = 0;

                $order = Db::name('order')->where($map)->find();

                if (!$order) api_return(0,'订单号错误');

                $price  = $order['price'];
                $subject = $this->title.'邀约';

                $body = json_encode([
                    'user_id'  => hashid($this->user_id),
                    'order_id' => $data['order_id'],
                    'type'     => $data['type'],
                    'subject'  => $subject
                ]);

                break;
            case 'noble': //贵族购买付款

                $noblePrice = $this->noblePrice($this->user_id);

                $price   = $noblePrice['price'];
                $subject = $this->title.'贵族购买';
                $noble['subject']    = $subject;
                $noble['user_id']    = hashid($this->user_id);
                $noble['type']       = $data['type'];
                $noble['price']      = $noblePrice['price'];
                $noble['give']       = $noblePrice['give'];
                $noble['noble_id']   = $noblePrice['noble_id'];
                $noble['noble_time'] = $noblePrice['noble_time'];
                $noble['noble_name'] = $noblePrice['noble_name'];

                $body = json_encode($noble);

                break;

            case 'guard': //守护购买付款

                $price = $this->guard_price($data['guard_type']);

                $data['user_id'] = $this->user_id;

                $this->checkGuard($data);

                if (!is_numeric($price) || $price < 1){
                    api_return(0,'参数错误');
                }

                $subject             = $this->title.'守护付费';
                $guard['subject']    = $subject;
                $guard['user_id']    = hashid($this->user_id);
                $guard['type']       = $data['type'];
                $guard['guard_type'] = $data['guard_type'];
                $guard['guard_user'] = $data['guard_user'];
                $guard['price']      = $price;
                $guard['room_id']    = $data['room_id']??0;
                $body = json_encode($guard);

                break;
            case 'member': //会员购买处理

                $price = MemberConfig::get($data['member_id'])['price'];

                $data['user_id'] = $this->user_id;

                if (!is_numeric($price) || $price < 1){
                    api_return(0,'参数错误');
                }

                //首充
                $con['user_id'] = $this->user_id;
                $con['pay_type'] = 1;

                $first = Db::name('bankroll')->where($con)->find();

                if ($first){
                    $is_first = 1;
                }else{
                    $is_first = 0;
                }

                $subject             = $this->title.'会员购买';
                $guard['subject']    = $subject;
                $guard['user_id']    = hashid($this->user_id);
                $guard['type']       = $data['type'];
                $guard['price']      = $price;
                $guard['member_id']  = $data['member_id'];
                $guard['is_first']   = $is_first;
                $guard['pay_type']   = 1;
                $body = json_encode($guard);

                break;
            case 'join': //门槛费

                if ($this->userInfo('is_pay') == 1){
                    api_return(0,'已付费,请勿重复操作!');
                }

                $reg_name = AppService::getUserInfo('register_name',$this->user_id);

                if ($reg_name == '陌生'){
                    $array['price'] = self::getExplain('ms_join_price');
                }else{
                    $array['price'] = self::getExplain('join_price');
                }

                $array['subject'] = $this->title.'注册费'.$array['price'];
                $array['user_id'] = hashid($this->user_id);
                $array['type']       = $data['type'];
                $price   = $array['price'];
                $subject = $array['subject'];

                $body = json_encode($array);
                break;

            case 'coin':
                $map['id']   = $data['id'];
                $config = Db::name('recharge')->where($map)->cache(2)->find();
                if (!$config || $config['price'] <= 0 || $config['first_price'] <= 0) api_return(0,'参数错误');

                //查询是否为首冲
                $where['user_id'] = $this->user_id;
                $where['money']   = $config['money'];

                $has = Db::name('bankroll')->where($where)->find();

                //首充
                $con['user_id'] = $this->user_id;
                $con['pay_type'] = 2;

                $first = Db::name('bankroll')->where($con)->find();

                if ($first){
                    $is_first = 0;
                }else{
                    $is_first = 1;
                }

                if ($has){
                    $price = $config['price'];
                }else{
                    $price = $config['first_price'];
                }

                $subject = $this->title.'心币充值'.$config['money'];

                $body = json_encode([
                    'user_id'  => hashid($this->user_id),
                    'id'       => $data['id'],
                    'type'     => $data['type'],
                    'remark'   => $subject,
                    'subject'  => $subject,
                    'is_first' => $is_first,
                    'pay_type' => 2
                ]);

                break;
            default:
                api_return(0,'类型错误');
                break;

        }
        $record['content']     = $body;
        $record['create_time'] = time();
        $record['update_time'] = time();
        $id = Db::name('paysign_record')->insertGetId($record);
        if (!$id) api_return(0,'记录错误');

        if (Env::get('is_test',false)){
            $price = 0.01;
        }

        if ($this->user_id == 20){
            $price = 0.01;
        }

        switch ($data['payType']){

            case 'alipay'://支付宝支付

                $order = [
                    'out_trade_no' => $order_num,
//                    'total_amount' => '0.01', //单位元
                'total_amount' => $price, //单位元
                    'subject' => $subject,
//                    'body' =>  $body,//自定义参数
                    'body' =>  $id,//自定义参数

                ];

                $sign = Pay::alipay($this->alipay)->app($order)->getContent();
                break;
            case 'wechat': //微信支付
                $order = [
                    'out_trade_no' => $order_num,
                    'body' => $subject,
//                    'total_fee' => '1',
                    'total_fee' => $price * 100, //单位 分
//                    'attach'=> $body,
                    'attach'=> $id,
                ];

                $json = Pay::wechat($this->wechat)->app($order)->getContent();
                $sign = json_decode($json,true);

                break;

            default:
                api_return(0,'支付类型错误');
                break;

        }
//        print_r($sign);exit;
        api_return(1,'获取成功',$sign);
    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 支付宝回调
     */
    public function notify()
    {

        $alipay = Pay::alipay($this->alipay);

        Db::startTrans();
        try{
            $data = $alipay->verify(); // 是，验签就这么简单！

            $map['out_trade_no'] = $data['trade_no'];
            $map['trade_no']     = $data['out_trade_no'];
            $map['pay_type']     = 1;

            $have = Db::name('pay_order')->where($map)->find();
            if ($have){ //订单已处理
                return $alipay->success()->send();
            }

            if ($data['trade_status'] == 'TRADE_SUCCESS' || $data['trade_status'] == 'TRADE_FINISHED'){

                $record = Db::name('paysign_record')->where('id',$data['body'])->value('content');
                if (!$record){
                    Log::record('查询不到支付签名记录');
                    cache('msg','查询不到支付签名记录'.$data['body']);
                    api_return(0,'查询不到支付签名记录');

                }
                $body = json_decode($record,true);

                switch ($body['type']){
                    case 'recharge'://充值
                        $body['money']  = $data['total_amount'];
                        $body['trade_type'] = 2;
                        $this->recharge($body,2);
                        break;

                    case 'member'://会员购买
                        $body['money']  = $data['total_amount'];

                        $this->memberHandle($body['member_id'],dehashid($body['user_id']),true);

                        $array['user_id']    = dehashid($body['user_id']);
                        $array['money']      = $data['total_amount'];
                        $array['remark']     = $body['subject']??'充值';
                        $array['type']       = 2;
                        $array['pay_money']  = $data['total_amount'];
                        $array['trade_type'] = 2;
                        $array['is_first']   = $body['is_first'];
                        $array['pay_type']   = $body['pay_type'];
                        self::rechargeRecord($array);

                        break;

                    case 'join'://门槛费
                        $body['trade_type'] = 2;

                        $this->join($body,$data['total_amount'],2);

                        break;

                    case 'gift': //礼物赠送

                        $this->gift($body);

                        $array['user_id']    = dehashid($body['user_id']);
                        $array['money']      = $data['total_amount'];
                        $array['remark']     = $body['subject']??'充值';
                        $array['type']       = 2;
                        $array['pay_money']  = $data['total_amount'];
                        $array['trade_type'] = 2;
                        self::rechargeRecord($array);

                        $this->addLevel($data['total_amount'],dehashid($body['user_id']));
                        break;

                    case 'invite': //邀约订单付款

                        $array['user_id']    = dehashid($body['user_id']);
                        $array['money']      = $data['total_amount'];
                        $array['remark']     = $body['subject']??'充值';
                        $array['type']       = 2;
                        $array['pay_money']  = $data['total_amount'];
                        $array['trade_type'] = 2;
                        self::rechargeRecord($array);

                        $order['out_trade_no'] = $data['trade_no'];
                        $order['trade_no']     = $data['out_trade_no'];
                        $order['out_price']    = $data['total_amount'];
                        $order['pay_way']      = 2;
                        $order['status']       = 1;
                        if ($this->invite($body,$order)){
                            $this->addLevel($data['total_amount'],dehashid($body['user_id']));
                        }
                        break;
                    case 'noble':

                        $array['user_id']    = dehashid($body['user_id']);
                        $array['money']      = $data['total_amount'];
                        $array['remark']     = $body['subject']??'充值';
                        $array['type']       = 2;
                        $array['pay_money']  = $data['total_amount'];
                        $array['trade_type'] = 2;
                        self::rechargeRecord($array);

                        if ($this->nobles($body)){
                            $this->addLevel($data['price'],dehashid($body['user_id']));
                        }

                        break;
                    case 'guard':

                        $array['user_id']    = dehashid($body['user_id']);
                        $array['money']      = $data['total_amount'];
                        $array['remark']     = $body['subject']??'充值';
                        $array['type']       = 2;
                        $array['pay_money']  = $data['total_amount'];
                        $array['trade_type'] = 2;
                        $body['user_id']    = dehashid($body['user_id']);
                        $body['guard_user'] = dehashid($body['guard_user']);
                        $body['type'] = $body['guard_type'];
                        $errorMsg = $this->guardOpen($body,1);

                        if ($errorMsg !== true){
                            throw new Exception($errorMsg,500);
                        }

                        self::rechargeRecord($array);

                        break;
                    case 'coin':
                        $array['remark']     = $body['remark'];
                        $array['user_id']    = dehashid($body['user_id']);
                        $array['id']         = $body['id'];
                        $array['pay_money']  = $data['total_amount'];
                        $array['trade_type'] = 2;
                        $array['is_first']   = $body['is_first'];
                        $array['pay_type']   = $body['pay_type'];
                        self::coinRecharge($array,2);
                        break;

                    default:

                        cache('msg','类型错误'.$data['body']);

                        api_return(0,'类型错误');
                        break;
                }

            }
            $item['out_trade_no'] = $data['trade_no'];
            $item['trade_no']     = $data['out_trade_no'];
            $item['type']         = $body['type'];
            $item['price']        = $data['total_amount'];
            if (is_numeric($body['user_id'])){
                $item['user_id']      = $body['user_id'];
            }else{
                $item['user_id']      = dehashid($body['user_id']);
            }
            $item['pay_type']     = 1;
            $item['create_time']  = time();
            $item['update_time']  = time();
            Db::name('pay_order')->insert($item);
            Db::commit();

//            Log::debug('Alipay notify', $data->all());
        } catch (Exception $e) {
            Db::rollback();
            cache('messageData',$data);
            cache('message',$e);
            dd('error');
//             exit('error');
        }

        return $alipay->success()->send();
    }


    public static function coinRecharge(array $data,$type)
    {
        $config = Db::name('recharge')->where('id',$data['id'])->find();

        if (!$config){
            api_return(0,'参数错误');
        }


        $string = '';

        if ($config['give'] > 0){
            $userInfo = self::getMemberFunc($data['user_id']);
            //赠送会员
            $string = '本次充值'.$config['give_explain'];
            $update = self::getMemberInfo($userInfo,['end_time_num'=>31*86400*$config['give']]);
            Db::name('user_extend')->where('user_id',$data['user_id'])->update($update);
        }

        $str = sprintf('您已成功充值%s心币，%s赶快进入App使用吧！如有疑问请及时与我们联系。',$config['money'],$string);
        self::sendUsrMsg('system',hashid($data['user_id']),$str);

        $record['user_id']    = $data['user_id'];
        $record['money']      = $config['money'];
        $record['remark']     = $data['remark'];
        $record['trade_type'] = isset($data['trade_type'])? $data['trade_type'] :$type;
        $record['type']       = $type;
        $record['pay_money']  = $data['pay_money'];
        $record['is_first']   = $data['is_first'];
        $record['pay_type']   = isset($data['pay_type'])? $data['pay_type'] :0;
        self::rechargeRecord($record);

        return Db::name('users')->where('user_id',$data['user_id'])->setInc('coin',$config['money']);

    }


    public function wechat()
    {

        $pay = Pay::wechat($this->wechat);

        try{

            $verify = $pay->verify(); // 是的，验签就这么简单！

            $map['out_trade_no'] = $verify['transaction_id'];
            $map['trade_no']     = $verify['out_trade_no'];
            $map['pay_type']     = 2;
            $have = Db::name('pay_order')->where($map)->find();
            if ($have){ //订单已处理
                return $pay->success()->send();
            }

            $record = Db::name('paysign_record')->where('id',$verify['attach'])->value('content');
            if (!$record){
                Log::record('查询不到支付签名记录');
                cache('msg','查询不到支付签名记录'.$verify['body']);
                api_return(0,'查询不到支付签名记录');
            }
            $body = json_decode($record,true);
//            $body = json_decode($verify['attach'],true);
            $total = $verify['cash_fee'] / 100;


            switch ($body['type']){
                case 'recharge'://充值
                    $body['money']  = $total;
                    $body['trade_type'] = 1;
                    $this->recharge($body,1);
                    break;

                case 'gift': //礼物赠送

                    $array['user_id']    = dehashid($body['user_id']);
                    $array['money']      = $total;
                    $array['remark']     = $body['subject']??'充值';
                    $array['type']       = 1;
                    $array['pay_money']  = $total;
                    $body['trade_type'] = 1;
                    self::rechargeRecord($array);

                    $this->gift($body);
                    $this->addLevel($total,dehashid($body['user_id']));
                    break;

                case 'invite': //邀约订单付款

                    $array['user_id']    = dehashid($body['user_id']);
                    $array['money']      = $total;
                    $array['remark']     = $body['subject']??'充值';
                    $array['type']       = 1;
                    $array['pay_money']  = $total;
                    $array['trade_type'] = 1;
                    self::rechargeRecord($array);

                    $order['out_trade_no'] = $verify['transaction_id'];
                    $order['trade_no']     = $verify['out_trade_no'];
                    $order['out_price']    = $total;
                    $order['pay_way']      = 3;
                    $order['status']       = 1;
                    if ($this->invite($body,$order)){
                        $this->addLevel($total,dehashid($body['user_id']));
                    }
                    break;
                case 'noble':

                    $array['user_id']    = dehashid($body['user_id']);
                    $array['money']      = $total;
                    $array['remark']     = $body['subject']??'充值';
                    $array['type']       = 1;
                    $array['pay_money']  = $total;
                    $array['trade_type'] = 1;
                    self::rechargeRecord($array);


                    if ($this->nobles($body)){
                        $this->addLevel($body['price'],dehashid($body['user_id']));
                    }

                    break;
                case 'guard': //守护

                    $array['user_id']    = dehashid($body['user_id']);
                    $array['money']      = $total;
                    $array['remark']     = $body['subject']??'充值';
                    $array['type']       = 1;
                    $array['pay_money']  = $total;
                    $array['trade_type'] = 1;
                    $body['user_id'] = dehashid($body['user_id']);
                    $body['guard_user'] = dehashid($body['guard_user']);
                    $body['type'] = $body['guard_type'];
                    $errorMsg = $this->guardOpen($body,1);
                    if ($errorMsg !== true){
                        throw new Exception($errorMsg,500);
                    }
                    self::rechargeRecord($array);

                    break;

                case 'member'://会员购买

                    $body['money']  = $body['total_amount'];

                    $this->memberHandle($body['member_id'],dehashid($body['user_id']),true);

                    $array['user_id']    = dehashid($body['user_id']);
                    $array['money']      = $total;
                    $array['remark']     = $body['subject']??'充值';
                    $array['type']       = 1;
                    $array['pay_money']  = $total;
                    $array['trade_type'] = 1;
                    $array['is_first']   = $body['is_first'];
                    $array['pay_type']   = $body['pay_type'];
                    self::rechargeRecord($array);
                    break;

                case 'join'://门槛费
                    $body['trade_type'] = 1;
                    $this->join($body,$total,1);

                    break;
                case 'coin':
                    $array['remark']     = $body['remark'];
                    $array['user_id']    = dehashid($body['user_id']);
                    $array['id']         = $body['id'];
                    $array['pay_money']  = $total;
                    $array['trade_type'] = 1;
                    $array['is_first']   = $body['is_first'];
                    $array['pay_type']   = $body['pay_type'];
                    self::coinRecharge($array,1);
                    break;
                default:
                    cache('msg','类型错误'.$verify['body']);
                    api_return(0,'类型错误');
                    break;
            }
            $item['out_trade_no'] = $verify['transaction_id'];
            $item['trade_no']     = $verify['out_trade_no'];
            $item['type']         = $body['type'];
            if (is_numeric($body['user_id'])){
                $item['user_id']      = $body['user_id'];
            }else{
                $item['user_id']      = dehashid($body['user_id']);
            }
            $item['price']        = $total;
            $item['pay_type']     = 2;
            $item['create_time']  = time();
            $item['update_time']  = time();
            Db::name('pay_order')->insert($item);
        } catch (Exception $e) {
            // $e->getMessage();
            cache('wechatMsgData',$e);
            cache('wechatMsg',$e);
            dd('error');

        }

        return $pay->success()->send();// laravel 框架中请直接 `return $pay->success()`
    }













    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 邀约修改
     */
    protected function invite($data,$order)
    {

        $model = new Logic();
        $model->changeTable('order');
        $map['status'] = 0;
        $map['order_id'] = $data['order_id'];

        $item = $model->where($map)->find();

        if (!$item || $item['status'] != 0){
            return false;
        }
        $online = $this->userExtra('online_status',$item['to_user']);
        if ($online != 1){
            $form_name = Db::name('skill_form')->where('form_id',$item['form_id'])->value('form_name');
            $skill = Db::name('skill')->where('skill_id',$item['skill_id'])->find();
            $phone = $this->userInfo('phone',$item['to_user']);
            $val['val1'] = substr($phone,-4,4);
            $val['val2'] = date('m月d日 H:i').'的'.$skill['skill_name']."($form_name)";
            //发送短信
            sendCustomSms($this->userInfo('phone',$item['to_user']),$val,'order');
        }
        return $item->save($order);

    }





    public static $errorMsg ;

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 支付宝退款
     */
    public  function aliRefund(array $order)
    {
        try{
            $alipay = Pay::alipay($this->alipay);
            $data =  $alipay->refund($order);
        }catch (\Exception $e){
             self::$errorMsg = $e->getMessage();
             return false;
        }

        if ($data['code'] == 10000  ){
//            if ($data['fund_change'] == 'N'){
//                self::$errorMsg = '支付宝退款失败';
//            }else{
                return true;
//            }
        }else{
            self::$errorMsg = $data['msg'];
        }
        return false;

    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 微信退款
     */
    public  function weChatRefund(array $order)
    {
        try{
            $pay = Pay::wechat($this->wechat);
            $data =  $pay->refund($order);
        }catch (\Exception $e){
//            dd($e->getMessage());
            self::$errorMsg = $e->getMessage();
            return false;
        }

        if ($data['return_code'] == 'SUCCESS' && $data['return_msg'] == 'ok'  ){
//            if ($data['fund_change'] == 'N'){
//                self::$errorMsg = '支付宝退款失败';
//            }else{
            return true;
//            }
        }else{
            self::$errorMsg = $data['return_msg'];
        }
        return false;
    }





}